package com.changgou.order.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.order.config.TokenDecode;
import com.changgou.order.pojo.MyCollection;
import com.changgou.order.service.CartService;
import com.changgou.order.service.MyCollectionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/cart")
public class CartController {
	@Autowired
	private CartService cartService;
	@Autowired
	private TokenDecode tokenDecode;
	@Autowired
	private MyCollectionService myCollectionService;
	 //添加购物车
	@GetMapping("/add")
	public Result add(@RequestParam("skuId") String skuId, @RequestParam("num") Integer num){
		//暂时静态,后续动态获取
		//String username = "itcast";
		String username = tokenDecode.getUserInfo().get("username");
		cartService.addCart(skuId,num,username);
		return new Result(true, StatusCode.OK,"加入购物车成功");
	}

	/***
	 * 查询用户购物车列表
	 * @return
	 */
	@GetMapping("/list")
	public Map list(){
		//暂时静态，后续修改
		//String username = "itcast";
		String username = tokenDecode.getUserInfo().get("username");
		return cartService.list(username);
	}
	/**
	 * 添加收藏
	 * @param skuId
	 * @return
	 */
	@PostMapping
	public Result addCol(@RequestParam("skuId") String skuId){
		String username = tokenDecode.getUserInfo().get("username");
		//查询是否到达收藏数
		Integer byIdCount = myCollectionService.findByIdCount(username);
		if (byIdCount>=20){
			return new Result(false,StatusCode.ERROR,"添加收藏失败");
		}
		MyCollection collection = new MyCollection();
		collection.setSku_id(Long.valueOf(skuId));
		collection.setUsername(username);
		cartService.addCol(collection);
		return new Result(true,StatusCode.OK,"添加收藏成功");
	}

}
